'use strict';

const { Controller } = require('egg');
const xml2json = require('xml2json');
const crypto = require('crypto');

class MpController extends Controller {
  verify() {
    const { ctx } = this;
    const { signature, timestamp, nonce, echostr } = ctx.query;
    if (!signature || !timestamp || !nonce || !echostr) ctx.body = '';
    else {
      const token = 'QDUYIiRT1Wi2O2RuJEKBnQy4erE3TIZJ';
      const list = [ token, timestamp, nonce ];
      list.sort();
      const code = crypto.createHash('sha1').update(list.join('')).digest('hex');
      if (code === signature) ctx.body = echostr;
      else ctx.body = '';
    }
  }

  toXml($1, $2, $3, $4, $5) {
    let xmlStr = '<xml>\n' +
      '  <ToUserName><![CDATA[$$1$$]]></ToUserName>\n' +
      '  <FromUserName><![CDATA[$$2$$]]></FromUserName>\n' +
      '  <CreateTime>$$3$$</CreateTime>\n' +
      '  <MsgType><![CDATA[$$4$$]]></MsgType>\n' +
      '  <Content><![CDATA[$$5$$]]></Content>\n' +
      '</xml>\n';
    xmlStr = xmlStr.replace('$$1$$', $1);
    xmlStr = xmlStr.replace('$$2$$', $2);
    xmlStr = xmlStr.replace('$$3$$', $3);
    xmlStr = xmlStr.replace('$$4$$', $4);
    xmlStr = xmlStr.replace('$$5$$', $5);
    return xmlStr;
  }

  async index() {
    const { ctx } = this;
    const json = JSON.parse(xml2json.toJson(this.ctx.request.body, {}));
    console.log(json);
    const { xml } = json;
    const obj = {
      xml: {
        ToUserName: xml.FromUserName,
        FromUserName: xml.ToUserName,
        CreateTime: (new Date() / 1000).toFixed(0),
        MsgType: 'text',
        Content: '',
      },
    };
    ctx.set('Content-Type', 'text/xml');
    try {
      obj.xml.Content = await ctx.service.mp.solve();
      if (obj.xml.Content === 'success') {
        ctx.body = 'success';
      } else {
        ctx.body = this.toXml(obj.xml.ToUserName, obj.xml.FromUserName, obj.xml.CreateTime, obj.xml.MsgType, obj.xml.Content);
      }
    } catch (e) {
      obj.xml.Content = e.message;
      ctx.body = this.toXml(obj.xml.ToUserName, obj.xml.FromUserName, obj.xml.CreateTime, obj.xml.MsgType, obj.xml.Content);
    }
    console.log(ctx.body);
  }
}

module.exports = MpController;
